<template>
  <div v-if="list && list.length" class="search-history">
    <div class="search-history-header">
      <span class="search-history-title">搜索历史</span>
      <van-icon name="delete" @click="clearHistory" />
    </div>
    <ul class="search-history-content">
      <li v-for="item in list" :key="item" class="search-history-item" @click="toList(item)">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
import { isEmpty } from '@/utils'
export default {
  props: {
    type: {
      type: [String],
      default() {
        return '1'
      }
    }
  },
  data() {
    return {
      // 所有的历史记录
      allList: {},
      // 当前类型的历史记录
      list: []
    }
  },
  created() {
    this.getAllHistory()
    if (isEmpty(this.allList)) {
      this.list = this.allList[this.type] || []
    }
  },
  mounted() {
    this.$nextTick(function() {
      this.$on('setHistory', (val) => {
        this.list.push(val)
        this.allList[this.type] = this.unique(this.list)
        localStorage.setItem('SearchHistory', JSON.stringify(this.allList))
        this.$emit('update:val', '')
      })
    })
  },
  methods: {
    // 获取所有历史记录
    getAllHistory() {
      this.allList = JSON.parse(localStorage.getItem('SearchHistory')) || {}
    },
    // 去重
    unique(arr) {
      return Array.from(new Set(arr))
    },
    // 清空搜索历史
    clearHistory() {
      this.list = []
      this.allList[this.type] = []
      localStorage.setItem('SearchHistory', JSON.stringify(this.allList))
    },
    toList(item) {
      this.$router.push({ name: 'HouseList', query: { name: item, type: this.type } })
    }
  }
}
</script>

<style scoped lang="less">
.search-history {
  padding: 0 @padding-15;
  .search-history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: @font-size-15;
    font-weight: @font-weight-bold;
    height: @header-height;
  }
  .search-history-item {
    display: inline-block;
    background: @gray-2;
    color: @gray-7;
    font-size: @font-size-13;
    line-height: @line-height-1;
    padding: 10px 15px;
    border-radius: @border-radius-sm;
    margin-right: 7px;
    margin-bottom: 11px;
  }
}
</style>
